<!--
 * @Description:sql编辑器
 * @Autor: HuiSir<273250950@qq.com>
 * @Date: 2022-01-05 16:07:46
 * @LastEditTime: 2022-01-06 10:37:12
-->
<template>
  <div class="sql-edit">
    <el-tabs v-model="tabValue" type="card" closable @tab-remove="removeTab">
      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
      />
    </el-tabs>
    <textarea ref="sqlEditor" class="code-sql" />
    <el-button class="add-btn" type="text" @click="addTab">
      +新增查询
    </el-button>
  </div>
</template>
<script>
import { format as sqlFormatter } from 'sql-formatter'

// 引入核心样式
import 'codemirror/theme/ambiance.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/addon/hint/show-hint.css'

// 引入全局实例
const CodeMirror = require('codemirror/lib/codemirror')

// 插件
require('codemirror/addon/edit/matchbrackets')
require('codemirror/addon/selection/active-line')

// sql语言包
require('codemirror/mode/sql/sql')

// 代码自动提示插件
require('codemirror/addon/hint/show-hint')
require('codemirror/addon/hint/sql-hint')

export default {
  name: 'SqlEdit',
  data() {
    return {
      tabValue: '1',
      editableTabs: [
        {
          title: '查询 1',
          name: '1',
          content: ''
        }
      ],
      tabIndex: 1,
      editor: null
    }
  },
  computed: {
    // 将编辑器中的值赋给newVal变量
    newVal() {
      if (this.editor) {
        return this.editor.getValue()
      }
    }
  },
  watch: {
    tabValue(val) {
      this.editor.setValue(
        this.editableTabs.find((item) => item.name === val).content
      )
    },
    newVal(val) {
      this.editableTabs.find((item) => item.name === this.tabValue).content =
        val
    }
  },
  mounted() {
    this.editor = CodeMirror.fromTextArea(this.$refs.sqlEditor, {
      value: '',
      mode: { name: 'text/x-mysql' },
      indentWithTabs: true,
      smartIndent: true,
      lineNumbers: true,
      matchBrackets: true,
      cursorHeight: 1,
      lineWrapping: true,
      readOnly: false,
      autofocus: true,
      extraKeys: { Ctrl: 'autocomplete' },
      hintOptions: {
        completeSingle: false,
        tables: this.tables
      }
    })

    // 监听inputRead事件，实现代码自动提示功能
    this.editor.on('inputRead', () => {
      this.editor.showHint()
    })
  },
  methods: {
    addTab() {
      const newTabName = ++this.tabIndex + ''
      this.editableTabs.push({
        title: '查询 ' + newTabName,
        name: newTabName,
        content: ''
      })
      this.editor.setValue('')
      this.tabValue = newTabName
    },
    removeTab(targetName) {
      const tabs = this.editableTabs
      let activeName = this.tabValue
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.name
            }
          }
        })
      }

      this.tabValue = activeName
      this.editableTabs = tabs.filter((tab) => tab.name !== targetName)
    },
    // 取值
    getValue() {
      return this.editor.getValue()
    },
    // 格式化
    fmt() {
      this.editor.setValue(sqlFormatter(this.getValue()))
    },
    // 清空
    empty() {
      this.editor.setValue('')
    }
  }
}
</script>
<style scoped lang="scss">
.sql-edit {
  ::v-deep .el-tabs {
    width: calc(100% - 100px);
    .el-tabs__header .el-tabs__item.is-active {
      background: #fff;
    }
    .el-tabs__header .el-tabs__nav {
      border-radius: 0;
      .el-tabs__item:first-child {
        span.el-icon-close {
          display: none;
        }
      }
    }
  }
  .add-btn {
    position: absolute;
    height: 41px;
    top: 5px;
    right: 15px;
    width: 70px;
    border-radius: 0;
  }
  ::v-deep .CodeMirror {
    border: 1px solid #ddd;
    margin-right: 5px;
  }
}
</style>
